package com.zzw.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.zzw.adapter.MyPagerAdapter;
import com.zzw.adapter.QuestionAdapter;
import com.zzw.util.BaseActivity;
import com.zzw.util.Globals;
import com.zzw.util.QuestionDao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseActivity {
    private ViewPager pager;
    private MyPagerAdapter pagerAdapter;
    private List<View> allViews;

    private TextView topTitle;
    private Button[] bottomBtns = new Button[3];

    //没有被选中时按钮的图片
    private int[] bottomImgs = new int[]{R.drawable.bottombtn01b, R.drawable.bottombtn02b, R.drawable.bottombtn03b};

    private int[] bottomImgsSelected = new int[]{R.drawable.bottombtn01a, R.drawable.bottombtn02a, R.drawable.bottombtn03a};

    private String[] allTitles = new String[]{getString(R.string.interview), getString(R.string.allquestion), getString(R.string.search)};

   /* private int i;*/

    private Button setting;
    private PopupWindow win;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 滑动显示的页面
        pager = (ViewPager) findViewById(R.id.pager);
        allViews = new ArrayList<>();
        View mainView = LayoutInflater.from(this).inflate(R.layout.page_main, null);
        View questionView = LayoutInflater.from(this).inflate(R.layout.page_question, null);
        View searchView = LayoutInflater.from(this).inflate(R.layout.page_search, null);
        allViews.add(mainView);
        allViews.add(questionView);
        allViews.add(searchView);

        initQuestionList(questionView);
        initSearch(searchView);

        //　设置最大显示页面数
        pager.setOffscreenPageLimit(3);
        //　将要显示的页面加入页面适配器
        pagerAdapter = new MyPagerAdapter(allViews);
        pager.setAdapter(pagerAdapter);

        // 页面切换
        pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                // 设置页面头部显示内容
                topTitle.setText(allTitles[position]);
                // 设置页面foot处按钮的显示
                for (int i = 0; i < bottomBtns.length; i++) {
                    if (i == position) {
                        bottomBtns[i].setBackgroundResource(bottomImgsSelected[i]);
                    } else {
                        bottomBtns[i].setBackgroundResource(bottomImgs[i]);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    //显示问题页面的ListView使用
    private ListView list;
    private List<Map<String, Object>> values;
    private QuestionAdapter adapter;
    //分页显示使用
    private int pagesize = 15;
    private int pagenum = 1;
    private int recordCount;
    private int pageCount;
    private int first;        // 第一个可见的条目
    private int visible;      // 可见的所有条目
    private int total;        // 每页显示的所有条目

    private String keyword;     // 查询关键字

    // 准备问题查询结果，并显示
    public void initQuestionList(View questionView) {
        list = (ListView) questionView.findViewById(R.id.list);
        if (keyword == null) {
            keyword = "";
        }
        //分页查询，从数据库中获取数据
        values = QuestionDao.loadDataPage(pagenum, pagesize, keyword);
        recordCount = QuestionDao.getCount(keyword);
        pageCount = (recordCount - 1) / pagesize + 1;
        //加入footerView
        final TextView footerView = new TextView(this);
        footerView.setText("正在加载数据，请稍候。。。。");
        footerView.setTextColor(Color.BLACK);
        footerView.setTextSize(12);
        list.addFooterView(footerView);

        adapter = new QuestionAdapter(this, values);
        list.setAdapter(adapter);

        // 设置问题点击事件
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map<String, Object> map = values.get(position);
                LinearLayout linear = (LinearLayout) view;
                if (linear.getChildCount() == 1) {
                    TextView answerView = new TextView(MainActivity.this);
                    answerView.setText(map.get("answer").toString());
                    answerView.setTextSize(14);
                    answerView.setTextColor(Color.RED);
                    linear.addView(answerView);
                    map.put("showFlag", true);
                } else {
                    linear.removeViewAt(1);
                    map.put("showFlag", false);
                }
            }
        });
        // 刷新显示其余内容
        list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_IDLE && first + visible == total && total != 0) {
                    if (pagenum < pageCount) {
                        pagenum++;
                        values.addAll(QuestionDao.loadDataPage(pagenum, pagesize, keyword));
                        adapter.notifyDataSetChanged();
                    } else {
                        if (list.getFooterViewsCount() > 0) {
                            list.removeFooterView(footerView);
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                first = firstVisibleItem;
                visible = visibleItemCount;
                total = totalItemCount;
            }
        });
    }

    // 搜索页面
    private EditText searchContent;
    private Button searchBtn;

    public void initSearch(View searchView) {
        searchBtn = (Button) searchView.findViewById(R.id.search_btn);
        searchContent = (EditText) searchView.findViewById(R.id.search_content);

        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keyword = searchContent.getText().toString();
                pagenum = 1;
                values.clear();
                values.addAll(QuestionDao.loadDataPage(pagenum, pagesize, keyword));
                adapter.notifyDataSetChanged();
                pager.setCurrentItem(1, true);
            }
        });
    }

    // 准备页面foot和head显示的内容
    public void init(String title, int index) {

        /*topTitle = (TextView) findViewById(R.id.top_title);
        topTitle.setText(title);

        bottomBtns[0] = (Button) findViewById(R.id.bottom_btn_01);
        bottomBtns[1] = (Button) findViewById(R.id.bottom_btn_02);
        bottomBtns[2] = (Button) findViewById(R.id.bottom_btn_03);
        for (i = 0; i < bottomBtns.length; i++) {
            final int temp = i;
            if (i == index) {
                bottomBtns[i].setBackgroundResource(bottomImgsSelected[i]);
            } else {
                bottomBtns[i].setBackgroundResource(bottomImgs[i]);
            }
            bottomBtns[i].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pager.setCurrentItem(temp, true);
                }
            });
        }*/

        setting = (Button) findViewById(R.id.setting);
        // setting按钮点击事件
        setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                win = new PopupWindow(Globals.SCREEN_WIDTH / 4, Globals.SCREEN_HEIGHT / 6);
                View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.win_list, null);
                win.setContentView(view);

                if (win.isShowing()) {
                    win.dismiss();
                } else {
                    //把浮动窗口置于设置按钮下方
                    win.showAsDropDown(setting);
                }

                TextView version = (TextView) view.findViewById(R.id.win_version);
                TextView about = (TextView) view.findViewById(R.id.win_about);
                TextView exit = (TextView) view.findViewById(R.id.win_exit);
                version.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        win.dismiss();
                        Toast.makeText(MainActivity.this, "当前为1.0.1版本", Toast.LENGTH_LONG).show();
                    }
                });

                about.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        win.dismiss();
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle("提示信息");
                        builder.setMessage("此应用为北航团队制作");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }

                        });
                        builder.create().show();
                    }
                });

                exit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
            }
        });
    }
}
